<template>
	<view>
		<view class="status_bar" :style="{height:statusBarHeightStyle}"></view>
		<uni-nav-bar :border="false" background-color="#00B5DD" color="#ffffff" left-icon="home"
			@clickLeft="goSwitch('/pages/home/home')"></uni-nav-bar>
		<view class="head">
			<uni-segmented-control :current="current" :values="items" :style-type="styleType"
				:active-color="activeColor" @clickItem="onClickItem" />
		</view>
		<view class="content">
			<view v-if="current === 0">
				<uni-forms ref="Form" :model="FormData" :rules="loginRules">
					<uni-forms-item class="form-item" name="accountName">
						<uni-easyinput :inputBorder="false" prefixIcon="phone" v-model="FormData.accountName"
							placeholder="请输入手机号">
						</uni-easyinput>
					</uni-forms-item>
					<uni-forms-item class="form-item" name="password" v-if="loginMethod == 'password'">
						<uni-row>
							<view class="uni-flex" style="align-items: center; justify-content: space-around;">
								<uni-col :span="18">
									<uni-easyinput :inputBorder="false" type="password" prefixIcon="locked"
										v-model="FormData.password" placeholder="请输入6至20位数字或字母">
									</uni-easyinput>
								</uni-col>
								<uni-col :span="6"><view><text class="form-link"
										@click="goTo('./exchangePassword/exchangePassword')">忘记密码？</text>
										</view>
								</uni-col>
							</view>
						</uni-row>
					</uni-forms-item>
					<uni-forms-item class="form-item" name="captcha" v-else>
						<uni-row>
							<view class="uni-flex" style="align-items: center; justify-content: space-around;">
								<uni-col :span="16">
									<uni-easyinput :inputBorder="false" prefixIcon="locked" v-model="FormData.captcha"
										placeholder="请输入验证码">
									</uni-easyinput>
								</uni-col>
								<uni-col :span="8">
									<view ><text class="form-link" v-if="isSend"
											@click="getCaptcha(FormData.accountName)">获取验证码</text><text
											v-else>{{time}}s</text></view>
								</uni-col>
							</view>
						</uni-row>
					</uni-forms-item>
					<view class="tips">
						<label class="radio" @click="loginReadClick(loginRead)">
							<checkbox value="read" :checked="loginRead" style="transform:scale(0.7)" />
							已阅读并同意<text @click="ontappopup('1')">《用户服务协议》</text>和<text
								@click="ontappopup('2')">《隐私政策》</text>
						</label>
					</view>
					<button :loading="loading" :disabled="loading" class="customer-btn"
						@click="submitLogin(FormData)">登录</button>
				</uni-forms>
				<view class="exchange" @click="exchangeLogin('captcha')" v-if="loginMethod == 'password'">短信验证码登录</view>
				<view class="exchange" @click="exchangeLogin('password')" v-else>密码登录</view>
			</view>
			<view v-show="current === 1">
				<uni-forms ref="registForm" :model="registFormData" :rules="registRules">
					<uni-forms-item name="accountName" class="form-item">
						<!-- <uni-row class="form-item">
							<uni-col :span="24">
								
							</uni-col>
						</uni-row> -->
						<uni-easyinput :inputBorder="false" prefixIcon="phone" v-model="registFormData.accountName"
							placeholder="请输入手机号">
						</uni-easyinput>
					</uni-forms-item>
					<uni-forms-item class="form-item" name="captcha">
						<uni-row>
							<view class="uni-flex" style="align-items: center; justify-content: space-around;">
								<uni-col :span="16">
									<uni-easyinput :inputBorder="false" prefixIcon="locked"
										v-model="registFormData.captcha" placeholder="请输入验证码">
									</uni-easyinput>
								</uni-col>
								<uni-col :span="8">
									<view style="text-align:right;"><text class="form-link" v-if="isSend"
											@click="getCaptcha(registFormData.accountName)">获取验证码</text><text
											v-else>{{time}}s</text></view>
								</uni-col>
							</view>
						</uni-row>
					</uni-forms-item>
					<uni-forms-item class="form-item" name="password">
						<uni-easyinput :inputBorder="false" prefixIcon="locked" v-model="registFormData.password"
							placeholder="请设置6位以上登录密码">
						</uni-easyinput>
						
					</uni-forms-item>
					<view class="tips">
						<label class="radio" @click="readClick">
							<checkbox value="yinsi" :checked="isRead" style="transform:scale(0.7)" />
							已阅读并同意<text @click="ontappopup('1')">《用户服务协议》</text>和<text
								@click="ontappopup('2')">《隐私政策》</text>
						</label>
					</view>
					<button :loading="loading" class="customer-btn" @click="registSubmit(registFormData)">注册</button>
				</uni-forms>
			</view>
		</view>
		<!-- #ifdef MP-WEIXIN -->
		<button class="bindPhone-btn" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">一键获取手机号码登录</button>
		<!-- #endif -->
		<uni-popup ref="popup" type="center">
			
		</uni-popup>
	</view>
</template>

<script>
	import {
		loginCaptcha,
		sendSmsCaptcha,
		registAccount,
		login,
		weChatLogin
	} from "@/api/user.js"

	import {
		MD5
	} from "@/utils/common.js"
	export default {
		data() {
			return {
				current: 0,
				items: ['登录', '注册'],
				activeColor: '#ffffff',
				styleType: 'text',
				FormData: {
					accountName: '',
					captcha: '',
					password: '',
				},

				registFormData: {
					accountName: '',
					captcha: '',
					password: '',
				},
				loginMethod: 'password',
				isRead: false,
				loginRead: false,
				loginRules: {
					accountName: {
						rules: [{
								required: true,
								errorMessage: '请输入手机号',
							},
							{
								minLength: 11,
								maxLength: 11,
								errorMessage: '输入有误，请输入11位的手机号码',
							}
						]
					},
					captcha: {
						rules: [{
							required: true,
							errorMessage: '请输入手机获取的验证码',
						}]
					},
				},
				registRules: {
					accountName: {
						rules: [{
								required: true,
								errorMessage: '请输入手机号',
							},
							{
								minLength: 11,
								maxLength: 11,
								errorMessage: '输入有误，请输入11位的手机号码',
							}
						]
					},
					captcha: {
						rules: [{
							required: true,
							errorMessage: '请输入手机获取的验证码',
						}]
					},
					password: {
						rules: [{
								required: true,
								errorMessage: '请设置6位以上的密码',
							},
							{
								minLength: 6,
								maxLength: 20,
								errorMessage: '请设置最少6位以上，不超过20位的密码',
							},
							{
								validateFunction: function(rule, value, data, callback) {
									var regx = /^[A-Za-z0-9]+$/
									if (!regx.test(value)) {
										callback('密码只能输入数字和字母')
									}
									return true
								}
							}
						]
					}
				},
				time: 0,
				timer: '',
				isSend: true,
				isSendR: true,
				timeR: 0,
				timerR: '',
				loading: false,
				statusBarHeightStyle: 44,
			};
		},
		onReady() {
			this.$nextTick(()=>{
				this.$refs.registForm.setRules(this.registRules)
			})	
		},
		onLoad() {
			console.log("loginon")
			/* let cookie = uni.getStorageSync('X-Token')
			uni.request({
				url:"https://1yj-rt.gfox.ltd/nongmao/nb-app/1.0.1/LoginService/queryCurrentAccount",
				data:{},
				method: "POST",
				header: {
					'Cookie': `X-Token=${cookie}`
				},
				success: (res) => {
				        console.log(res.data);
				        if(res.data.msgCode != "common.starter.eduservice.needLogin"){
							uni.switchTab({
								url:"/pages/home/home"
							})
						}
				    },
				fail: (fail) => {
					console.log('fail', fail)
					return reject(fail);
				},
			}) */
		},
		onShow() {
			this.statusBarHeightStyle = getApp().globalData.statusBarHeight + 'px';
			//this.windowWidth = getApp().globalData.windowWidth;
			//this.navBarWidth = getApp().globalData.navBarWidth;
			//this.navBarHeight = getApp().globalData.navBarHeight;
		},
		onHide() {
			clearInterval(this.timer);
		},
		methods: {
			async loginCaptcha(options) {
				setTimeout(() => {
					this.loading = false;
				}, 3000)
				const res = await loginCaptcha(options);
				let username = res.returnObj.nickName
				uni.setStorageSync('X-Token', res.returnObj.token)
				uni.setStorageSync('username', username)
				uni.switchTab({
					url: '/pages/home/home'
				});
				
				/* if(res.success){
					uni.switchTab({
						url: '/pages/home/home'
					});
				} */
			},
			async registAccount(options) {
				setTimeout(() => {
					this.loading = false;
				}, 3000)
				const res = await registAccount(options);
				if (res.success) {
					uni.showToast({
						title: "注册成功！"
					})
					uni.switchTab({
						url: '/pages/home/home'
					});
				}
			},
			async login(options) {
				setTimeout(() => {
					this.loading = false;
				}, 3000)
				const res = await login(options);
				if (res.success) {
					uni.showToast({
						title: "登录成功！"
					})
					let username = res.returnObj.nickName
					uni.setStorageSync('X-Token', res.returnObj.token)
					uni.setStorageSync('username', username)
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/home/home'
						});
					}, 500)
				}
				//this.loading = false;
			},
			getCaptcha(parmas) {
				if (parmas) {
					console.log("phone", parmas)
					sendSmsCaptcha(parmas).then((res) => {
						console.log("res", res)
						this.time = 60;
						this.isSend = false;
						this.timer = setInterval(() => {
							this.time = this.time - 1;
							if (this.time <= 0) {
								this.isSend = true;
							}
						}, 1000)
						uni.showToast({
							title: '验证码发送成功！'
						})

					}).catch((err) => {

					})
				} else {
					uni.showToast({
						title: '请输入手机号码！'
					})
					return
				}
			},
			onClickItem(e) {
				console.log("ceshi", e)
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex
				}
			},
			submitLogin(options) {
				if (!this.loginRead) {
					uni.showToast({
						title: '请先勾选隐私协议！'
					})
					return
				}
				this.loading = true;
				/* this.login(
					{
					       "accountName": "sysAdmin",                         // 登录账号/手机号
					       "password": "Root@123"                               // 登录密码
					
				}); */
				this.$refs.Form.validate().then(res => {
					console.log('表单数据信息：', res);
					if (res.password) {
						res.password = MD5(res.password);
					}
					if (this.loginMethod == 'password') {
						this.login(res)
					} else {
						this.loginCaptcha(res);
					}
				}).catch(err => {
					console.log('表单错误信息：', err);
				})

			},
			registSubmit(options) {
				console.log(this.isRead)
				if (!this.isRead) {
					uni.showToast({
						title: '请先勾选隐私协议！'
					})
					return
				}
				this.loading = true;
				this.$refs.registForm.validate().then(res => {
					console.log('表单数据信息：', res);
					res.password = MD5(res.password);
					setTimeout(() => {
						this.registAccount(res);
					}, 1000)

				}).catch(err => {
					console.log('表单错误信息：', err);
				})
				//this.loading = false;
			},
			readClick() {
				this.isRead = !this.isRead;
				console.log("read", this.isRead)
			},
			loginReadClick() {
				this.loginRead = !this.loginRead;
				console.log("read", this.loginRead)
			},
			exchangeLogin(e) {
				this.loginMethod = e;
				console.log('method', this.loginMethod);
			},
			goTo(e) {
				var url = e;
				uni.navigateTo({
					url: url
				})
			},
			goSwitch(e) {
				var url = e;
				uni.reLaunch({
					url: url
				})
			},
			ontappopup(t) {
				if (t == "1") {
					this.$refs.popup.open()
				} else {
					this.$refs.popYinsi.open()
				}
				console.log("1111111")
			},
			onGetPhoneNumber(e) {
				console.log("手机", e)
				if (e.detail.errMsg == "getPhoneNumber:ok") {
					console.log("用户点击了接受")
					console.log(e.detail);
					let obj = {
						code: e.detail.code
					}
					//用户点击接受后 你会拿到和之前获取基本信息一样的iv 和en 几个参数 传递给后端，后端调取微信官方的接口并且进行解密 再回传手机号到前台
					weChatLogin(obj).then(res => {
						console.log(res, '获取到的手机号');
						if (res.success) {
							uni.showToast({
								title: "登录成功！"
							})
							let username = res.returnObj.nickName
							uni.setStorageSync('X-Token', res.returnObj.token)
							uni.setStorageSync('username', username)
							setTimeout(() => {
								uni.switchTab({
									url: '/pages/home/home'
								});
							}, 500)
						}
					})
				} else {
					console.log("用户拒绝了获取手机号!")
				}
			},

		}
	}
</script>

<style lang="scss">
	page {
		background-image: url("https://staticfile-yj.obs.cn-north-4.myhuaweicloud.com/login-bg.png");
		background-repeat: no-repeat;
		background-size: 100% auto;
		background-color: #ffffff;
	}

	.head {
		padding-top: 150px;
	}

	/deep/.segmented-control__item {
		width: 220rpx;
		display: inline-block;
		flex: inherit;
		color: #ffffff;
	}

	/deep/.segmented-control__text {
		color: #ffffff !important;
		font-size: 44rpx;
		opacity: 0.6
	}

	/deep/.segmented-control__item--text {
		font-size: 48rpx;
		opacity: 1
	}

	.segmented-control {
		padding: 0 30rpx;
	}

	.content {
		margin-top: 20px;
		background-color: #ffffff;
		border-radius: 16px 16px 0 0;
		padding: 30px 30rpx;
	}

	.form-item {
		display: flex;
		flex-flow: row nowrap;
		justify-content: space-between;
		align-items: center;
		background-color: #F4F5F6;
		border-radius: 50px;
		margin-bottom: 15px;
	}

	/deep/.uni-easyinput__content {
		background: none !important;
	}

	.form-link {
		font-size: 28rpx;
		color: #283241;
	}

	.tips {
		margin-top: 64px;

		.radio {
			font-size: 28rpx;
			color: #283241;
		}

	}

	.radio text {
		color: #00B5DD;
	}

	.customer-btn {
		background-color: #00B5DD !important;
		color: #fff;
		border-radius: 8px;
		height: 44px;
		line-height: 44px;
		font-size: 32rpx;
		font-weight: 500;
		margin-top: 20px;
	}

	.exchange {
		font-size: 24rpx;
		text-align: center;
		color: #00B5DD;
		line-height: 22px;
		margin-top: 15px;
	}

	.pop-content {
		background: #ffffff;
		line-height: 20px;
		font-size: 24rpx;
		width: 80%;
		height: 500px;
		overflow-y: scroll;
		margin: 0 auto;
		padding: 30rpx;

		.title {
			font-size: 28rpx;
			font-weight: bold;
			text-align: center;
		}
	}

	.bindPhone-btn {
		position: fixed;
		bottom: 0;
		width: 100%;
		height:45px;
		line-height: 35px;
		font-size: 28rpx;
		color: #00B5DD;
		background-color: #ffffff;
	}

	.bindPhone-btn::after {
		border: none !important;
	}
</style>